package torpedoserver;

import com.sun.xml.internal.ws.resources.SenderMessages;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.OutputStream;
import messages.Message;
import messages.WelcomeMessage;
import playerthreads.Player1Thread;
import playerthreads.Player2Thread;

public class PlayerHandlerThread extends Thread {
    private int port;
    private ServerSocket serverSocket;
    Socket player1,
           player2;
    public static boolean player1Ready = false,
                          player2Ready = false;
    public static PlayerHandlerThread PlayerHandlerThread = new PlayerHandlerThread(12345);

    private PlayerHandlerThread(int port) {
        this.port = port;
        System.out.println("PortListening");
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("SocketOpen");
        } catch (IOException ex) {
            Logger.getLogger(PlayerHandlerThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void run() {
        try {
            player1 = serverSocket.accept();
            System.out.println(player1.isConnected());
            SendMess(player1, new WelcomeMessage("Player1"));
            player2 = serverSocket.accept();
            System.out.println("sdasdadaaaaaaaa");
            SendMess(player2, new WelcomeMessage("Player2"));
            Player1Thread p1 = new Player1Thread(player1);
            Player2Thread p2 = new Player2Thread(player2);
            p1.start();
            p2.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void SendMess(Socket s, Message mess) throws IOException{
        OutputStream os = s.getOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeObject(mess);
        oos.flush();
    }
}